import os
import asyncio
import threading

from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from controller import modelExperienceController
from service.neuttsAirService import neuttsAirModel
from service.removeOutputFileService import clearnOutdated
from utils.loggingConfig import get_logger
root_path = os.path.dirname(os.path.abspath(__file__))

logger = get_logger('')

def __initEnv():
    env_path = os.path.join(root_path , 'env')
    env_path = os.path.abspath(env_path)
    load_dotenv(dotenv_path=env_path, verbose=True)
    for k , v in dict(os.environ).items():
        logger.info(f'{k} -> {v}')

def __initModel():
    # 初始化模型：
    try:
        import torch_npu
        device = "npu" if torch_npu.npu.is_available() else 'cpu'
    except Exception as e :
        device = 'cpu'

    backbone_device = device
    codec_device = device
    neuttsAirModel(backbone_device , codec_device)

def __init():
    __initEnv()

    # asyncio.gather(clearnOutdated())
    # __initModel()

__init()

t = threading.Thread(target=clearnOutdated)
t.start()


def getApp():
    app = FastAPI()
    modelExperienceController.fapp = app
    # 解决跨域的问题
    app.add_middleware(
        CORSMiddleware,
        allow_origins=['*'],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # 注册路由
    app.include_router(modelExperienceController.router)

    return app